package com.mp.approvalreq.servlet;

import com.alibaba.fastjson.JSONObject;
import com.mp.approvalreq.entity.Request;
import com.mp.approvalreq.service.ApprovalOperateServicePrx;
import com.mp.approvalreq.util.ServiceUtils;
import com.mp.user.entity.User;
import com.plusmoney.exception.RpcServerLogicalException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 作废某人的审批
 *
 * @author Administrator
 */
@WebServlet("/abortSomeonesRequest")
public class AbortSomeonesRequest extends AbstractServlet {

    private static final Logger logger = LoggerFactory.getLogger(AbortSomeonesRequest.class);

    /**
     * 数据格式:{requestDkey:,templateId:,version:}
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
     throws ServletException, IOException {
        try {
            User user = getReqUser(req);

            Request request = getRequest(req);

            ApprovalOperateServicePrx approvalOperateServicePrx = ServiceUtils.getApprovalOperateServicePrx();
            request.setUser(user);
            approvalOperateServicePrx.cancelRequest(request);

            printResult(resp);
        } catch (Throwable e) {
            onThrowable(req, resp, e);
        }
    }

    private void printResult(HttpServletResponse resp) throws IOException {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("result", "0");
        jsonObject.put("res_info", "作废成功");

        logger.info(jsonObject.toJSONString());

        printJson(resp, jsonObject.toJSONString());
    }

    private Request getRequest(HttpServletRequest req) throws IOException {
        String reqBody = getContent(req);
        logger.info("json参数值 {}", reqBody);

        Request request;
        try {
            request = JSONObject.parseObject(reqBody, Request.class);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new RpcServerLogicalException(1, "审批内容提交失败，请稍候再试");
        }
        return request;
    }
}
